#!/bin/bash -ex

function check_dir() {
  local build_dir=$1
  if [ -e $build_dir ]; then
    echo "[$(date +"%Y-%m-%d %T")] The folder $build_dir already exists. Do you want to remove (Y) it or reuse? Y/[N]"
    read -r answer
    if [[ -n $answer ]]; then
      solution=$(echo "$answer" | tr '[:lower:]' '[:upper:]')
    else
      solution='N'
    fi

    if [ $solution = 'Y' ]; then
      echo "[$(date +"%Y-%m-%d %T")] Going to remove and recreate $build_dir"
      rm -rf $build_dir
      mkdir -p $build_dir
    else
      echo "[$(date +"%Y-%m-%d %T")] The folder $build_dir is kept. Let's reuse it"
    fi
  else
      echo "[$(date +"%Y-%m-%d %T")] Going to create $build_dir"
      mkdir -p $build_dir
  fi
}

function get_toolchain() {
  echo "-DCMAKE_TOOLCHAIN_FILE=cmake/toolchain/host_clang_14.cmake"
}

function get_ASAN_options() {
  echo "-DPANDA_ENABLE_UNDEFINED_BEHAVIOR_SANITIZER=true -DPANDA_ENABLE_ADDRESS_SANITIZER=true"
}

function get_TSAN_options() {
  echo "-DPANDA_ENABLE_THREAD_SANITIZER=true -DPANDA_ENABLE_UNDEFINED_BEHAVIOR_SANITIZER=false -DPANDA_ENABLE_ADDRESS_SANITIZER=false"
}

function get_fastverify() {
  echo "-DCMAKE_BUILD_TYPE=FastVerify"
}

function get_debug() {
  echo "-DCMAKE_BUILD_TYPE=DEBUG"
}

function run_cmake_ninja() {
  local source_dir=$1
  local build_dir=$2
  local build_type=$3
  local toolchain=$4
  local options=$5
  local processes=$6
  local targets=$7

  local start=$(date +%s)
  echo "[$(date +"%Y-%m-%d %T")] Start $build_dir"

  check_dir $build_dir

  cd $build_dir || exit 1

  echo "[$(date +"%Y-%m-%d %T")] RUN: cmake $source_dir $build_type $toolchain $options -GNinja"
  cmake $source_dir $build_type $toolchain $options -GNinja

  echo "[$(date +"%Y-%m-%d %T")] RUN: ninja -j $processes $targets"
  ninja -j $processes $targets

  finish=$(date +%s)
  duration_s=$((finish-start))
  duration_min=$((duration_s/60))

  echo "[$(date +"%Y-%m-%d %T")] End ~" $duration_min "min or" $duration_s "s"

}
